<template>
  <div class="app-container">
    <div class="app-title">
      <span>机构人员维护</span>
    </div>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-col :span="1">
          <i :class="[treeShow ? 'el-icon-s-fold treeI': 'el-icon-s-unfold treeI']" @click="toggerTree" />
        </el-col>
      </el-col>
      <el-col :span="12" style="text-align: right;margin-top:-8px;margin-bottom:10px">
         <el-button size="small" class="filter-item" style="margin-left: 10px;" type="primary" @click="moreQuery">
          查询
        </el-button>
        <el-button size="small" class="filter-item" style="margin-left: 10px;" type="primary" @click="personnelCode">
          编辑人员编码
        </el-button>
        <el-button size="small" class="filter-item" style="margin-left: 10px;" type="primary" @click="handleAdddepts">
          编辑人员排序
        </el-button>
        <el-button size="small" class="filter-item" style="margin-left: 10px;" type="primary" @click="handleAdddept">
          挂接科室
        </el-button>
      </el-col>
    </el-row>
    <div
      ref="box"
      class="box"
    >
      <div
        class="left"
        :class="[isActive ? 'wid':'wids']"
      >
        <div
          :class="[treeShow ? 'treeShow' : 'treeNotShow']"
          :style="{'height' : treeHeight + 'px'}"
        >
          <AgencyTree
            class="agencyTree"
            @handleTreeQuery="handleTreeQuery"
             @getFirstAuthAgencyData="getFirstAuthAgencyData"
          />
        </div>
      </div>
      <div
        v-show="Show"
        class="resize"
        title="收缩侧边栏"
      />
      <div
        class="mid"
        :class="[isActive ? 'mids': 'min']"
      >
        <el-dialog
          v-dialogDrag
          title="查询"
          :visible.sync="dialogQueryVisible"
          :close-on-click-modal="false"
          width="50%"
          style="padding:0px"
        >
          <el-form :model="listQuery" label-position="right" label-width="100px" class="dialog-backgroundcolor" size="small">
            <el-row>
              <el-col :span="12">
                <el-form-item label="人员姓名：">
                  <el-input v-model="listQuery.personName" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="身份证号码：">
                  <el-input v-model="listQuery.idenNo" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="人员编码：">
                  <el-input v-model="listQuery.personnelCode" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col style="text-align: right; margin-top: 1%">
                <el-button size="small" class="filter-item" style="margin-left: 10px;" type="primary" @click="handleFilter">
                  查询
                </el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-dialog>
        <el-table
          ref="singalTable"
          v-loading="listLoading"
          :data="list"
          :stripe="true"
          fit
          :height="tableHeight"
          :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        >
          <template slot="empty">
            <tableEmpty />
          </template>
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column type="index" align="center" width="50" label="序号" />
          <el-table-column label="单位名称" align="center">
            <template slot-scope="{row}">
              <span>{{ row.agencyName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="所在科室" align="center">
            <template slot-scope="{row}">
              <span>{{ row.deptId | deptFilter(that) }}</span>
            </template>
          </el-table-column>
           <el-table-column label="人员编码" align="center">
            <template slot-scope="{row}">
              <span>{{ row.personnelCode }}</span>
            </template>
          </el-table-column>
          <el-table-column label="人员姓名" align="center">
            <template slot-scope="{row}">
              <span>{{ row.personName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="性别" align="center">
            <template slot-scope="{row}">
              <span>{{ row.sexCode | sexFilter(that) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="身份证号码" align="center">
            <template slot-scope="{row}">
              <span>{{ row.idenNo  }}</span>
            </template>
          </el-table-column>
          <el-table-column label="排序" align="center">
            <template slot-scope="{row}">
              <span>{{ row.showOrder }}</span>
            </template>
          </el-table-column>
        </el-table>
        <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
      </div>
      <Drag ref="icon" />
    </div>
    <!-- 挂接页面 -->
    <el-dialog
      v-dialogDrag
      title="挂接科室"
      :visible.sync="addFormVisible"
      :close-on-click-modal="false"
      width="20%"
    >
      <el-form ref="addForm" class="addForm dialog-backgroundcolor" :rules="addFormRules" :model="formData" label-position="top" label-width="100px">
        <el-row>
          <span class="selectSpan">请选择科室：</span>
          <el-form-item prop="deptId">
            <el-select ref="selectReport" v-model="formData.deptName" class="filter-item" placeholder="--请选择--" :clearable="clearable" style="margin-left:16px" @clear="clearHandle">
              <el-option :value="formData.deptId" :label="formData.deptName" style="width: 300px;height:200px;overflow: auto;background-color:#fff">
                <el-tree
                  :data="listTree"
                  :accordion="accordion"
                  :props="defaultProps"
                  :node-key="defaultProps.id"
                  :default-expanded-keys="defaultExpandedKey"
                  @node-click="handleNodeClick"
                />
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row class="addButRow">
          <el-button type="primary" @click="handleAdddeptDialog">
            保存
          </el-button>
          <el-button @click="addFormVisible = false">
            取消
          </el-button>
        </el-row>
      </el-form>
    </el-dialog>
    <!--排序-->
    <el-dialog
      v-dialogDrag
      :close-on-click-modal="false"
      title="人员排序"
      :visible.sync="dialogVerifyFormVisible"
      style="padding: 0px"
      width="45%"
    >
      <el-form
        ref="dataForm"
        class="dialog-Backgroundcolor"
        :model="formData"
        label-position="right"
        label-width="0px"
      >
        <el-row>
          <el-button
            size="small"
            class="filter-item"
            style="margin-left: 10px; float: right"
            type="primary"
            :loading="saveLoading"
            @click="dialogVerifyFormVisible = false"
          >
            取消
          </el-button>
          <el-button
            size="small"
            class="filter-item"
            style="margin-left: 10px; float: right"
            type="primary"
            :loading="saveLoading"
            @click="handleSave"
          >
            保存
          </el-button>
        </el-row>
        <el-table
          ref="singalEditTable"
          v-loading="ListLoading"
          max-height="400"
          :data="editListData"
          :stripe="true"
          fit
          class="editTable"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
        >
          <!-- 一个填写框   scope.row.personNum 对应实体的值 -->
          <el-table-column fixed="right" label="单位名称" align="center" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.agencyName"
                disabled
                style="width:auto"
                maxlength="200"
              />
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="人员姓名" align="center" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.personName"
                disabled
                style="width:auto"
                maxlength="200"
              />
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="性别" align="center" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.sexCode"
                disabled
                style="width:auto"
                maxlength="200"
              />
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="排序" align="center" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.showOrder"
                 onkeyup="this.value=this.value.replace(/\D/g,'')" onafterpaste="this.value=this.value.replace(/\D/g,'')"
                style="width:auto"
                maxlength="9"
              />
            </template>
          </el-table-column>

        </el-table>
      </el-form>
    </el-dialog>
    <!--  人员编码 -->
     <el-dialog
      v-dialogDrag
      :close-on-click-modal="false"
      title="人员编码"
      :visible.sync="addFormPersonnelCode"
      style="padding: 0px"
      width="53%"
    >
      <el-form
        ref="dataForm"
        class="dialog-Backgroundcolor"
        :model="formData"
        label-position="right"
        label-width="0px"
      >
        <el-row>
          <el-button
            size="small"
            class="filter-item"
            style="margin-left: 10px; float: right"
            type="primary"
            :loading="saveLoading"
            @click="addFormPersonnelCode = false"
          >
            取消
          </el-button>
          <el-button
            size="small"
            class="filter-item"
            style="margin-left: 10px; float: right"
            type="primary"
             :loading="saveLoading"
            @click="personnelSave"
          >
            保存
          </el-button>
        </el-row>
        <el-table
          ref="singalEditTable"
          v-loading="ListLoading"
          max-height="400"
          :data="editListData"
          :stripe="true"
          fit
          class="editTable"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
        >
          <!-- 一个填写框   scope.row.personNum 对应实体的值 -->
          <el-table-column fixed="right" label="单位名称" align="center" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.agencyName"
                disabled
                style="width:auto"
                maxlength="200"
              />
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="人员姓名" align="center" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.personName"
                disabled
                style="width:auto"
                maxlength="200"
              />
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="性别" align="center" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.sexCode"
                disabled
                style="width:auto"
                maxlength="200"
              />
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="排序" align="center" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.showOrder"
                 disabled
                style="width:auto"
                maxlength="200"
              />
            </template>
          </el-table-column>
         <el-table-column fixed="right" label="人员编码" align="center" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.personnelCode"
                style="width:auto"
                maxlength="30"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { getPersonInfoList, updatePersonInfoList, updatePersonExtList ,updatePersonnelCodeList } from '@/api/personInfoMaintenance/personChangeEdit'
import { getDepartmentList, getDepartmentTree } from '@/api/unitInformationMaintenance/internalOrganizationMaintenance'
import { getSex,
  getSalaryState, } from '@/api/baseInfo'//人员编码限制onkeyup="this.value=this.value.replace(/\D/g,'')" onafterpaste="this.value=this.value.replace(/\D/g,'')"
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import tableEmpty from '@/components/table/empty'
import AgencyTree from '@/components/tree/agencyTree'
import Drag from '@/components/Drag'
export default {
  name: 'UnitInformationMaintenance',
  components: { Pagination, tableEmpty, AgencyTree, Drag },
  directives: { waves },
  filters: {
    changeFlag(type, that) {
      return that.unitName
    },
    // 性别过滤器
    sexFilter(type, that) {
      const sexLists = that.sexLists
      for (const item in sexLists) {
        if (sexLists[item].code === type) {
          return sexLists[item].name
        }
      }
    },
    // 部门过滤器
    deptFilter(type, that) {
      const deptLists = that.deptLists
      for (const item in deptLists) {
        if (deptLists[item].code === type) {
          return deptLists[item].name
        }
      }
    },
    //号码脱敏显示
    hideMiddle(val) {
      if(val !== undefined&& val !== null){//避免列表中存在空数据报错
        return `${val.substring(0,4)}****${val.substring(val.length-4)}`
      }else{
        return val
      }
    }
  },
  props: [],
  data() {
    return {
      tableHeight: null,
      that: this,
      clearable: true,
      accordion: false,
      treeShow: false,
      isActive: true,
      listTree: null,
      treeHeight: null,
      Show: false,
      saveLoading: false,
      ListLoading: false,
      dialogVerifyFormVisible: false,
      defaultExpandedKey: [],
      editListData: [],
      unitName: this.$store.getters.userInfo.agencyName,
      registerNum: '0',
      quitNum: '0',
      list: null,
      total: 0,
      listLoading: true,
      defaultProps: {
        id: 'id',
        children: 'children',
        label: 'label'
      },
      listQuery: {
        page: 1,
        limit: 200,
        meritPayCode: '',
        posCode: '',
        grCode: '',
        personName: '',
        idenNo: '',
        flag: 'all',
        agencyId: '',
        personnelCode:''
      },
      formData: {
        id: '',
        state: '',
        agencyCode: this.$store.getters.userInfo.agencyCode,
        agencyName: '',
        agencyId: '',
        personName: '',
        sexCode: '',
        deptId: '',
        deptName: '',
        idenNo: ''
      },
      addFormVisible: false,
      addFormPersonnelCode:false,
      sexLists: this.$store.getters.sexLists, // 性别
      deptLists: [], // 部门科室
      operatePersonLists: [], // 操作人集合
      addFormRules: {
        deptId: [
          { required: true, message: '请选择科室', trigger: 'blur' }
        ]
      },
      dialogQueryVisible: false
    }
  },
  watch: {
    // 表格的数据数组
    list(val) {
      this.doLayout()
    }
  },
  // 程序最先进入这里 页面在显示之前走的方法
  created() {
    // 1.页面在显示之前走的方法
    this.initBaseInfo()
    // 2.走这里
    this.getList()
    this.getTree()
  },
  mounted() {
    this.getTbHeight()
  },
  beforeMount() {
    window.addEventListener('resize', this.getTbHeight)
  },
  methods: {
    // 获取table高度的方法
    getTbHeight() {
      this.tableHeight = window.innerHeight - 208
    },
    /* 重新渲染table组件 */
    doLayout() {
      this.$nextTick(() => {
        this.$refs.singalTable.doLayout()
      })
    },
    dragController() {
      this.$refs.icon.dragControllerDiv()
    },
    getTbHeight() {
      this.tableHeight = window.innerHeight - 220
      this.treeHeight = this.tableHeight
    },
    toggerTree() {
      this.treeShow = !this.treeShow
      this.isActive = !this.isActive
      this.Show = !this.Show
    },
    handleTreeQuery(data) {
      this.treeData = data
      this.handleTree(data)
    },
    handleTree(data) {
      this.listQuery.agencyId = data.id
      this.initBaseInfo()
      this.getTree()
      this.getList()
    },
     // 树返回默认单位信息查询
     getFirstAuthAgencyData(data) {
      this.listQuery.agencyId = data.id
      this.getList()
    },
    getList() {
      //获取审核状态
      this.getSalaryState()
      // 将listLoading的值变为true显示页面
      this.listLoading = true
      // 将listQuery初始数据传入getPersonInfoList方法获取response的值
      getPersonInfoList(this.listQuery).then(response => {
        // 将里面的rows数据放到list里
        this.list = response.data.rows
        // 将里面的total数据放到total中
        this.total = response.data.total
        // 将listLoading变为false 显示页面完成
        this.listLoading = false
      })
    },
    handleFilter() {
      this.dialogQueryVisible = false
      // 将listQuery中的page改为1
      this.listQuery.page = 1
      // 然后走这个方法
      this.getList()
    },
    // 查询
    moreQuery() {
      this.listQuery = Object.assign({}, this.listQuery, '')
      this.dialogQueryVisible = true
    },
    restetFormData() {
      this.formData = {
        id: '',
        state: this.formData.state,
        agencyCode: this.$store.getters.userInfo.agencyCode,
        agencyName: '',
        personName: '',
        sexCode: '',
        deptId: '',
        deptName: '',
        idenNo: ''
      }
    },
    // 打开选择人员页面
    handleAdddept() {
        if (this.salaryState === 1) {
          this.$message({
            showClose: true,
            message: '工资编报已送审，不能操作',
            type: 'warning',
            duration: 4000
          })
          return
        }
      this.clearHandle()
      this.operatePersonLists.splice(0, this.operatePersonLists.length)
      // 将从表格别名为singalTable中获取的数据selection赋值给selection
      const selection = this.$refs.singalTable.selection
      // 如果选值不等于1是
      if (selection.length === 0) {
        // 将请最少选择一条数据返回
        this.$message({
          showClose: true,
          message: '请至少选择一条数据',
          type: 'warning',
          duration: 4000
        })
        return
      }
      this.formData.deptId = ''
      selection.forEach(item => {
        this.operatePersonLists.push(item)
      })
      // 将selection数组的下标为0的数据赋值给formData
      this.formData = Object.assign({}, this.formData, '')
      // 把addFormVisible变成true显示挂接页面
      this.addFormVisible = true
      this.$nextTick(() => {
        this.$refs['addForm'].clearValidate()
      })
    },
    // 挂接科室按钮
    handleAdddeptDialog() {
      // 将addForm表格中获取到的值
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          this.operatePersonLists.forEach(item => {
            item.deptId = this.formData.deptId
          })
          updatePersonInfoList(this.operatePersonLists).then((response) => {
            // 把addFormVisible改为false关闭挂在页
            this.addFormVisible = false
            // 输出更新成功和状态码
            // this.$notify({
            this.$message({
              // title: 'Success',
              showClose: true,
              message: '挂接成功',
              type: 'success',
              duration: 4000
            })
            // 然后走这个方法
            this.handleFilter()
          })
        }
      })
    },
    initBaseInfo() {
      // 通过调用getSex()方法 获取性别然后
      // getSex().then((response) => {
      //   // 将数据赋值给sexLists
      //   this.sexLists = Object.assign({}, response.data)
      // })
      // 将listQuery中的初始值传给getDepartmentList获取分页数据
      getDepartmentList(this.listQuery).then((response) => {
        // 将获取到的值赋值给deptLists
        this.deptLists = Object.assign({}, response.data)
      })
    },
    // 树点击
    handleNodeClick(data) {
      this.formData.deptId = data.id
      this.formData.deptName = data.label
      if (this.formData.deptName === '组织机构') {
        this.formData.deptId = ''
        this.formData.deptName = ''
      } else {
        this.$refs.selectReport.blur()
      }
    },
    // 清除下拉树选中
    clearHandle() {
      this.formData.deptName = ''
      this.formData.deptId = null
      this.defaultExpandedKey = []
    },
    // 获取数内容
    getTree() {
      getDepartmentTree(this.listQuery).then(response => {
        this.listTree = response.data
      })
    },
     handleAdddepts() {
        if (this.salaryState === 1) {
          this.$message({
            showClose: true,
            message: '工资编报已送审，不能操作',
            type: 'warning',
            duration: 4000
          })
          return
        }
      const queryPersonInfo = []
      // 获取当前 点击的数据
      const selection = this.$refs.singalTable.selection
      if (selection.length === 0) {
        // 将请最少选择一条数据返回
        this.$message({
          showClose: true,
          message: '请至少选择一条数据',
          type: 'warning',
          duration: 4000
        })
        return
      }
      // 获取第一条的数据
      // this.formData = Object.assign({}, this.formData, selection[0])
      // 循环 存入queryPersonInfo中
      selection.forEach(item => {
        const current = {}
        current['id'] = item.id
        current['agencyName'] = item.agencyName
        current['personName'] = item.personName
        current['deptId'] = item.deptId
        if (item.sexCode === '1') {
          current['sexCode'] = '男'
        } else {
          current['sexCode'] = '女'
        }
        current['showOrder'] = item.showOrder
        queryPersonInfo.push(current)
      })
      // 将queryPersonInfo 赋值给 this.editListData
      this.editListData = queryPersonInfo
      // 打开页面
      this.dialogVerifyFormVisible = true
    },
    handleSave() {
      this.saveLoading = true
      // 创建一个集合数组
      const postIds = []
      // 获取当前值
      const editListData = this.unique()
      // 将当前的存入 map 循环存入 返回给后台
      editListData.forEach(item => {      
        // 创建一个map
        const current = {}
        current['personId'] = item.id
        current['showOrder'] = item.showOrder
        // 将map 存入集合组数中
        postIds.push(current)
      })
      // 接口 插入或者保存
      updatePersonExtList(postIds).then((response) => {
        this.dialogEditFormVisible = false
        this.$message({
          showClose: true,
          message: '修改成功',
          type: 'success',
          duration: 4000
        })
        this.saveLoading = false
        this.dialogVerifyFormVisible = false
        // 保存后调用刷新方法
        this.handleFilter()
      }).catch(() => {
        this.saveLoading = false
      })
    },// 人员排序按钮
      personnelCode() {
        if (this.salaryState === 1) {
          this.$message({
            showClose: true,
            message: '工资编报已送审，不能操作',
            type: 'warning',
            duration: 4000
          })
          return
        }
      const queryPersonInfo = []
      // 获取当前 点击的数据
      const selection = this.$refs.singalTable.selection
      if (selection.length === 0) {
        // 将请最少选择一条数据返回
        this.$message({
          showClose: true,
          message: '请至少选择一条数据',
          type: 'warning',
          duration: 4000
        })
        return
      }
      // 获取第一条的数据
      // this.formData = Object.assign({}, this.formData, selection[0])
      // 循环 存入queryPersonInfo中
      selection.forEach(item => {
        const current = {}
        current['id'] = item.id
        current['agencyName'] = item.agencyName
        current['personName'] = item.personName
        current['deptId'] = item.deptId
        if (item.sexCode === '1') {
          current['sexCode'] = '男'
        } else {
          current['sexCode'] = '女'
        }
        current['showOrder'] = item.showOrder
        current['personnelCode'] = item.personnelCode
        queryPersonInfo.push(current)
      })
      // 将queryPersonInfo 赋值给 this.editListData
      this.editListData = queryPersonInfo
      // 打开页面
      this.addFormPersonnelCode = true
    },
     personnelSave() {
      this.saveLoading = true
      // 创建一个集合数组
      const postIds = []
      // 获取当前值
      const editListData = this.unique()
      // 将当前的存入 map 循环存入 返回给后台

      editListData.forEach(item => {
        // 创建一个map
        const current = {}
        current['personId'] = item.id
        current['personnelCode'] = item.personnelCode
        // 将map 存入集合组数中
        postIds.push(current)
      })
      //接口 插入或者保存
      updatePersonnelCodeList(postIds).then((response) => {
        this.dialogEditFormVisible = false
        this.$message({
          showClose: true,
          message: '修改成功',
          type: 'success',
          duration: 4000
        })
        this.saveLoading = false
        this.addFormPersonnelCode = false
        // 保存后调用刷新方法
        this.handleFilter()
      }).catch(() => {
        this.saveLoading = false
      })
    },
    // 获取当前值
    unique() {
      const editListData = this.editListData
      return editListData
    },
    // 查询工资编报状态
    getSalaryState() {
      getSalaryState(this.listQuery).then(response => {
        this.salaryState = response.data.is_submit_in_agency
      })
    },
  }
}
</script>
<style lang="scss" scoped>
  .selectSpan {
    font-weight: 600;
   margin-left: 16px;
  }
  .addButRow {
    margin-top: 2%;
    text-align: right;
  }
</style>
